<template>
  <div class="membership-level-management">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item :label="$t('page.system.membershipLevel.levelName')">
          <el-input
            v-model="searchForm.levelName"
            :placeholder="$t('page.system.membershipLevel.levelName')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.membershipLevel.levelCode')">
          <el-input
            v-model="searchForm.levelCode"
            :placeholder="$t('page.system.membershipLevel.levelCode')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.membershipLevel.periodType')">
          <el-select
            v-model="searchForm.periodType"
            :placeholder="$t('page.system.membershipLevel.periodType')"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="option in periodTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('page.system.membershipLevel.isFree')">
          <el-select
            v-model="searchForm.isFree"
            :placeholder="$t('page.system.membershipLevel.isFree')"
            clearable
            style="width: 120px"
          >
            <el-option :label="$t('page.system.membershipLevel.yes')" :value="1" />
            <el-option :label="$t('page.system.membershipLevel.no')" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            {{ $t('page.system.membershipLevel.search') }}
          </el-button>
          <el-button @click="handleReset">
            {{ $t('page.system.membershipLevel.reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        + {{ $t('page.system.membershipLevel.add') }}
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        {{ $t('page.system.membershipLevel.batchDelete') }}
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      />
      <el-table-column
        prop="levelName"
        :label="$t('page.system.membershipLevel.levelName')"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="levelCode"
        :label="$t('page.system.membershipLevel.levelCode')"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="price"
        :label="$t('page.system.membershipLevel.price')"
        min-width="100"
        align="center"
      >
        <template #default="{ row }">
          <span v-if="row.isFree === 1" class="free-tag">
            {{ $t('page.system.membershipLevel.free') }}
          </span>
          <span v-else>
            ¥{{ row.price }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="periodType"
        :label="$t('page.system.membershipLevel.periodType')"
        width="100"
        align="center"
      >
                 <template #default="{ row }">
           <el-tag :type="getPeriodTypeTagType(row.periodType) as any">
             {{ getPeriodTypeTextDynamic(row.periodType) }}
           </el-tag>
         </template>
      </el-table-column>
      <el-table-column
        prop="periodValue"
        :label="$t('page.system.membershipLevel.periodValue')"
        width="100"
        align="center"
      />
      <el-table-column
        prop="maxContentCount"
        :label="$t('page.system.membershipLevel.maxContentCount')"
        width="120"
        align="center"
      />
      <el-table-column
        prop="isFree"
        :label="$t('page.system.membershipLevel.isFree')"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag :type="row.isFree === 1 ? 'success' : 'warning'">
            {{ row.isFree === 1 ? $t('page.system.membershipLevel.yes') : $t('page.system.membershipLevel.no') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdTime"
        :label="$t('page.system.membershipLevel.createdTime')"
        width="160"
        align="center"
      />
      <el-table-column
        :label="$t('page.system.membershipLevel.operation')"
        width="250"
        align="center"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            text
            @click="handleDetail(row)"
          >
            {{ $t('page.system.membershipLevel.detail') }}
          </el-button>
          <el-button
            size="small"
            type="primary"
            text
            @click="handleEdit(row)"
          >
            {{ $t('page.system.membershipLevel.edit') }}
          </el-button>
          <el-button
            size="small"
            type="danger"
            text
            @click="handleDelete(row)"
          >
            {{ $t('page.system.membershipLevel.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 会员等级表单弹窗 -->
    <MembershipLevelForm
      v-model:visible="formVisible"
      :form-data="currentLevel"
      :is-edit="isEdit"
      @submit="handleFormSubmit"
    />

    <!-- 会员等级详情弹窗 -->
    <MembershipLevelDetail
      v-model:visible="detailVisible"
      :level-data="currentLevel"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import type { MembershipLevel, MembershipLevelListParams, PeriodType } from '#/api/system/membership-level';
import { 
  deleteMembershipLevelsApi, 
  getMembershipLevelDetailApi, 
  getMembershipLevelListApi,
  getPeriodTypesApi,
  PERIOD_TYPE_OPTIONS
} from '#/api/system/membership-level';
import { $t } from '#/locales';

import MembershipLevelDetail from './components/MembershipLevelDetail.vue';
import MembershipLevelForm from './components/MembershipLevelForm.vue';

// 搜索表单
const searchForm = reactive<MembershipLevelListParams>({
  levelName: '',
  levelCode: '',
  periodType: undefined,
  isFree: undefined,
});

// 表格数据
const tableData = ref<MembershipLevel[]>([]);
const loading = ref(false);
const selectedRows = ref<MembershipLevel[]>([]);

// 分页
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

// 表单弹窗
const formVisible = ref(false);
const currentLevel = ref<Partial<MembershipLevel>>({});
const isEdit = ref(false);

// 详情弹窗
const detailVisible = ref(false);

// 周期类型选项（动态获取）
const periodTypeOptions = ref<Array<{ value: number; label: string }>>([]);
const periodTypeMap = ref<Map<number, PeriodType>>(new Map());

// 获取周期类型数据
const getPeriodTypes = async () => {
  try {
    try {
      const response = await getPeriodTypesApi();
      console.log('周期类型API响应:', response);
      console.log('response类型:', typeof response);
      console.log('response结构:', JSON.stringify(response, null, 2));
      
      let periodTypes: PeriodType[] = [];
      
      // 尝试多种响应格式解析
      if (response && (response as any).code === 200 && (response as any).data) {
        // 格式1: { code: 200, message: "成功", data: [...] }
        console.log('使用格式1解析 - 标准包装格式');
        periodTypes = (response as any).data as PeriodType[];
      } else if (response && (response as any).data && (response as any).data.code === 200) {
        // 格式2: { data: { code: 200, message: "成功", data: [...] } }
        console.log('使用格式2解析 - 双层包装格式');
        periodTypes = (response as any).data.data as PeriodType[];
      } else if (response && Array.isArray(response)) {
        // 格式3: 直接返回数组 [...]
        console.log('使用格式3解析 - 直接数组格式');
        periodTypes = response as PeriodType[];
      } else if (response && Array.isArray((response as any).data)) {
        // 格式4: { data: [...] }
        console.log('使用格式4解析 - 简单包装格式');
        periodTypes = (response as any).data as PeriodType[];
      } else {
        console.error('周期类型API响应格式异常:', response);
        throw new Error('API响应格式不符合预期');
      }
      
      console.log('解析后的周期类型数据:', periodTypes);
      
      // 验证数据有效性
      if (!Array.isArray(periodTypes) || periodTypes.length === 0) {
        throw new Error('周期类型数据为空或格式错误');
      }
      
      // 转换为选项格式
      periodTypeOptions.value = periodTypes.map(type => ({
        value: type.code,
        label: type.name
      }));
      
      // 存储到Map中便于快速查找
      periodTypeMap.value.clear();
      periodTypes.forEach(type => {
        periodTypeMap.value.set(type.code, type);
      });
      
      console.log('周期类型选项:', periodTypeOptions.value);
      console.log('周期类型映射:', periodTypeMap.value);
      console.log('✅ 周期类型数据加载成功!');
    } catch (apiError: any) {
      console.error('周期类型API调用失败:', apiError);
      console.error('API错误详情:', {
        message: apiError?.message || '未知错误',
        status: apiError?.response?.status || '无状态码',
        statusText: apiError?.response?.statusText || '无状态文本',
        url: apiError?.config?.url || '无URL',
        method: apiError?.config?.method || '无方法'
      });
      ElMessage.error('获取周期类型失败');
      
      // 清空选项数据
      periodTypeOptions.value = [];
      periodTypeMap.value.clear();
    }
  } catch (error) {
    console.error('获取周期类型失败:', error);
    ElMessage.error('获取周期类型失败');
  }
};

// 获取周期类型文本（使用动态数据）
const getPeriodTypeTextDynamic = (periodType: number) => {
  const periodTypeData = periodTypeMap.value.get(periodType);
  return periodTypeData ? periodTypeData.name : `类型${periodType}`;
};

// 获取周期类型标签颜色
const getPeriodTypeTagType = (periodType: number) => {
  const colorMap: { [key: number]: string } = {
    1: 'info',     // 天卡
    2: 'success',  // 周卡
    3: 'primary',  // 月卡
    4: 'warning',  // 季卡
    5: 'danger',   // 年卡
  };
  return colorMap[periodType] || 'info';
};

// 获取会员等级列表
const getMembershipLevelList = async () => {
  loading.value = true;
  try {
    // 过滤掉空值参数，只传入有值的查询条件
    const params: any = {
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
    };
    
    // 只有当搜索条件有值时才添加到参数中
    if (searchForm.levelName && searchForm.levelName.trim()) {
      params.levelName = searchForm.levelName.trim();
    }
    if (searchForm.levelCode && searchForm.levelCode.trim()) {
      params.levelCode = searchForm.levelCode.trim();
    }
    if (searchForm.periodType !== undefined && searchForm.periodType !== null) {
      params.periodType = searchForm.periodType;
    }
    if (searchForm.isFree !== undefined && searchForm.isFree !== null) {
      params.isFree = searchForm.isFree;
    }

    const response = await getMembershipLevelListApi(params);
    console.log("会员等级API响应数据：", response);

    // 检查API响应格式
    if (response && (response as any).data && (response as any).data.code === 200) {
      const responseData = (response as any).data.data;
      console.log("解析后的数据：", responseData);
      tableData.value = responseData?.result || [];
      pagination.total = responseData?.total || 0;
      console.log("表格数据：", tableData.value);
      console.log("总数：", pagination.total);
    } else if (response && (response as any).result && Array.isArray((response as any).result)) {
      // 直接使用API返回的数据结构
      console.log("使用API数据");
      tableData.value = (response as any).result || [];
      pagination.total = (response as any).total || 0;
    } else {
      console.error('会员等级API响应格式异常:', response);
      tableData.value = [];
      pagination.total = 0;
      ElMessage.error('API响应格式异常，请检查接口');
    }
  } catch (error) {
    console.error('获取会员等级列表失败:', error);
    ElMessage.error('获取会员等级列表失败');
  } finally {
    loading.value = false;
  }
};



// 搜索
const handleSearch = () => {
  pagination.pageNo = 1;
  getMembershipLevelList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    levelName: '',
    levelCode: '',
    periodType: undefined,
    isFree: undefined,
  });
  pagination.pageNo = 1;
  getMembershipLevelList();
};

// 新增
const handleAdd = () => {
  currentLevel.value = {
    periodType: 3,    // 默认月卡
    periodValue: 30,  // 默认30天
  };
  isEdit.value = false;
  formVisible.value = true;
};

// 编辑
const handleEdit = (row: MembershipLevel) => {
  currentLevel.value = { ...row };
  isEdit.value = true;
  formVisible.value = true;
};

// 查看详情
const handleDetail = async (row: MembershipLevel) => {
  try {
    const response = await getMembershipLevelDetailApi(row.id);
    console.log('会员等级详情API响应:', response);
    
    // 检查API响应格式
    if (response && (response as any).levelName) {
      // 直接返回会员等级详情数据
      console.log('使用API返回的会员等级详情数据');
      currentLevel.value = response as unknown as MembershipLevel;
      detailVisible.value = true;
    } else if (response && (response as any).data && (response as any).data.code === 200) {
      // 包装格式的API响应
      console.log('使用包装格式的会员等级详情数据');
      currentLevel.value = (response as any).data.data;
      detailVisible.value = true;
    } else {
      console.error('会员等级详情API响应格式异常:', response);
      ElMessage.error('获取会员等级详情失败');
    }
  } catch (error) {
    console.error('获取会员等级详情失败:', error);
    ElMessage.error('获取会员等级详情失败');
  }
};

// 删除
const handleDelete = async (row: MembershipLevel) => {
  try {
    await ElMessageBox.confirm(
      $t('page.system.membershipLevel.message.deleteConfirm'),
      $t('page.system.membershipLevel.confirm'),
      {
        confirmButtonText: $t('page.system.membershipLevel.confirm'),
        cancelButtonText: $t('page.system.membershipLevel.cancel'),
        type: 'warning',
      }
    );

    const response = await deleteMembershipLevelsApi([row.id]);
    console.log('删除会员等级API响应:', response);
    
    if (response && ((response as any).success || (response as any).data?.code === 200)) {
      ElMessage.success($t('page.system.membershipLevel.message.deleteSuccess'));
      getMembershipLevelList();
    } else {
      ElMessage.error('删除会员等级失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除会员等级失败:', error);
      ElMessage.error('删除会员等级失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的会员等级');
    return;
  }

  try {
    await ElMessageBox.confirm(
      $t('page.system.membershipLevel.message.batchDeleteConfirm'),
      $t('page.system.membershipLevel.confirm'),
      {
        confirmButtonText: $t('page.system.membershipLevel.confirm'),
        cancelButtonText: $t('page.system.membershipLevel.cancel'),
        type: 'warning',
      }
    );

    const levelIds = selectedRows.value.map(row => row.id);
    
    const response = await deleteMembershipLevelsApi(levelIds);
    if (response && ((response as any).success || (response as any).data?.code === 200)) {
      ElMessage.success($t('page.system.membershipLevel.message.batchDeleteSuccess'));
      selectedRows.value = [];
      getMembershipLevelList();
    } else {
      ElMessage.error('批量删除会员等级失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }
};

// 选择变更
const handleSelectionChange = (selection: MembershipLevel[]) => {
  selectedRows.value = selection;
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageNo = 1;
  getMembershipLevelList();
};

// 页码变更
const handleCurrentChange = (page: number) => {
  pagination.pageNo = page;
  getMembershipLevelList();
};

// 表单提交
const handleFormSubmit = () => {
  formVisible.value = false;
  getMembershipLevelList();
};

// 页面加载
onMounted(async () => {
  // 先获取周期类型数据，然后获取会员等级列表
  await getPeriodTypes();
  getMembershipLevelList();
});
</script>

<style scoped>
.membership-level-management {
  padding: 20px;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.toolbar .el-button {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.free-tag {
  color: #67c23a;
  font-weight: bold;
}
</style> 
 